package com.my.study.service.Impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.my.study.convert.UserInfoConvert;
import com.my.study.convert.UserPersonConvert;
import com.my.study.dto.LoginLogDTO;
import com.my.study.dto.UserInfoDTO;
import com.my.study.entity.User;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.enums.LoginLogTypeEnum;
import com.my.study.exception.BusinessException;
import com.my.study.mapper.UserMapper;
import com.my.study.service.LoginLogService;
import com.my.study.service.UserInfoService;
import com.my.study.utils.JsonUtil;
import com.my.study.utils.JwtUtil;
import com.my.study.vo.UserInfoVO;
import com.my.study.vo.UserPersonVO;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPersonConvert userPersonConvert;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private UserInfoConvert userInfoConvert;


    @Override
    public UserPersonVO queryUserInfo(UserInfoDTO userInfo, HttpServletResponse response) {
        User user = new User();
        user.setNickname(userInfo.getUserName());
        user.setPassword(userInfo.getPassword());
        // 查询用户
        List<UserInfoVO> userInfoVOList = userMapper.queryUserInfo(user);
        if (Objects.isNull(userInfoVOList) || userInfoVOList.isEmpty()) {
            throw BusinessException.fail(BusinessExceptionEnum.SC_FORBIDDEN.code, BusinessExceptionEnum.SC_FORBIDDEN.msg);
        }
        UserPersonVO userPersonVO = userInfoConvert.toTarget(userInfoVOList.get(0));
        // 返回用户信息
        userPersonVO.setRoleList(userPersonConvert.toEntityList(userInfoVOList));
        // 响应添加cookie
        Map<String, Object> stringObjectMap = JsonUtil.ObjectToEntity(userPersonVO,
                new TypeReference<Map<String, Object>>() {
                });
        String token = JwtUtil.createToken(stringObjectMap);
        Cookie cookie = new Cookie("Cookie", token);
        response.addCookie(cookie);
        response.addHeader("token",token);
        // 异步记录日志
        taskExecutor.execute(() -> saveLoginLog(LoginLogTypeEnum.LOGIN, userPersonVO));
        return userPersonVO;
    }

    /**
     * 记录日志
     *
     * @param logTypeEnum
     * @param userPerson
     */
    public void saveLoginLog(LoginLogTypeEnum logTypeEnum, UserPersonVO userPerson) {
        LoginLogDTO loginLog = new LoginLogDTO();
        loginLog.setId(UuidUtil.getTimeBasedUuid().toString().replaceAll("-", ""));
        loginLog.setLoginTime(new Date());
        loginLog.setOperationType(logTypeEnum.value);
        loginLog.setUserId(userPerson.getUserId());
        loginLog.setUserName(userPerson.getUserName());
        loginLogService.addLoginLog(loginLog);
    }
}
